<template>
  <div class="search-container">
    <a-input-search class="search" placeholder="输入内容以搜索" search-button @search="search"/>
  </div>
  <a-button style="margin-left: 20px" status="danger" @click="deleteBatchQuestionBank">删除</a-button>
  <a-button style="margin-left: 20px" status="success" @click="addQuestionBank">添加</a-button>
  <a-table
      style="padding: 20px"
      row-key="id"
      :data="data"
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="false"
      :page-position="'bottom'"
      :stripe="true"
  >
    <template #columns>
      <a-table-column title="题库图标" align="center">
        <template #cell="{record}">
          <a-avatar shape="square" :image-url="record.bankIcon!=null?record.bankIcon:'https://stone-answer-bucket-1328818493.cos.ap-chengdu.myqcloud.com/bank_icon/default_icon.png'" :size="32" />
        </template>
      </a-table-column>
      <a-table-column title="题库名称" data-index="title" :ellipsis="true" :tooltip="true" align="center"></a-table-column>
      <a-table-column title="标签" align="center">
        <template #cell="{record}">
          <!-- 修改 v-for 循环，只渲染前两个标签 -->
          <a-tag style="margin-right: 5px" v-for="(tag, index) in JSON.parse(record.tags).slice(0, 2)" :key="index">
            {{tag}}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column title="点赞数" data-index="thumbNum" align="center"></a-table-column>
      <a-table-column title="收藏数" data-index="favourNum" align="center"></a-table-column>
      <a-table-column title="创建时间" data-index="createTime" align="center"></a-table-column>
      <a-table-column title="更新时间" data-index="updateTime" align="center"></a-table-column>
      <a-table-column title="操作" align="center">
        <template #cell="{record}">
          <a-button style="margin-right: 5px" size="mini" status="danger" @click="deleteQuestionBank(record.id)">删除
          </a-button>
          <a-button size="mini" type="primary" @click="editQuestionBank(record.id)">修改</a-button>
        </template>
      </a-table-column>

    </template>
  </a-table>
  <div style="display: flex; justify-content: center; margin-top: 10px; margin-bottom: 10px;">
    <a-pagination
        :total="pageInfo.total"
        :current="pageInfo.current"
        :page-size="pageInfo.pageSize"
        show-jumper
        show-page-size
        @change="listQuestionBank"
        @page-size-change="changePageSize"
    />
  </div>
  <a-modal
      v-model:visible="confirmVisible"
      @ok="doDeleteBank"
      :closable="false"
  >
    <div style="text-align: center">
      确认删除？
    </div>
  </a-modal>
  <a-drawer :width="450" :visible="editVisible" @ok="doEditBank" @cancel="clearContent" unmountOnClose>
    <template #title>
      {{ editBankInfo.title }}
    </template>
    标题：
    <a-input :placeholder="editBankInfo.title" v-model="editBankInfo.title"/>
    <div style="margin-top: 20px">
      标签：
      <a-tag
          style="margin-right: 5px"
          v-for="(tag) of editBankInfo.tags"
          :key="tag"
          :closable = "true"
          @close="handleRemove(tag)"
      >
        {{ tag }}
      </a-tag>
      <a-input
          v-if="showInput"
          ref="inputRef"
          :style="{ width: '90px'}"
          size="mini"
          v-model.trim="inputVal"
          @keyup.enter="handleAdd"
          @blur="handleAdd"
      />
      <a-tag
          v-else
          :style="{
        width: '90px',
        backgroundColor: 'var(--color-fill-2)',
        border: '1px dashed var(--color-fill-3)',
        cursor: 'pointer',
      }"
          @click="handleEdit"
      >
        <template #icon>
          <icon-plus/>
        </template>
        Add Tag
      </a-tag>
    </div>

    <file-upload @onProgress="onProgress"></file-upload>
  </a-drawer>
</template>

<script setup>
// 列名
import { IconPlus } from '@arco-design/web-vue/es/icon';
import {nextTick, onMounted, reactive, ref} from "vue";
import {
  addQuestionBankUsingPost,
  deleteBatchQuestionBankUsingPost,
  deleteQuestionBankUsingPost, getQuestionBankVOByIdUsingGet,
  listQuestionBankByPageUsingPost, updateQuestionBankUsingPost
} from "@/api/QuestionBankRequest";
import FileUpload from "@/components/FileUpload.vue";
import {uploadFileUsingPost} from "@/api/FileRequest";
// 题库列表
const data = ref([]);
// 选择的题库数据
const selectedKeys = ref([]);

// 搜索框输入的内容
const inputContent = ref("")
// 选项框配置信息
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
});
// 分页配置信息
const pageInfo = ref({
  pageSize: 5,
  current: 1,
  total: 50
});

// 当前要删除的题库ID
let delBankId = ref(0);
// 提示框是否展示
let confirmVisible = ref(false);
// 修改框是否展示
let editVisible = ref(false);
// 当前正在编辑的题库信息
let editBankInfo = ref({
  title: '',
  tags: []
});
const inputRef = ref(null);
const showInput = ref(false);
const inputVal = ref('');

// 当前正在上传的题库图标
const file = ref();


// 记录当前正在执行的操作
let curOperate = "update";

// 获取题库信息
onMounted(async () => {
  await listQuestionBank(1);
})

// 获取题库信息的具体方法
async function listQuestionBank(current) {
  const result = await listQuestionBankByPageUsingPost({
    current: current,
    pageSize: pageInfo.value.pageSize,
    searchText: inputContent.value
  });
  pageInfo.value.current = current;
  pageInfo.value.total = result.data.data.total;
  data.value = result.data.data.records;
}

async function changePageSize(pageSize) {
  pageInfo.value.pageSize = pageSize;
  await listQuestionBank(pageInfo.value.current);
}

function search( content ) {
  inputContent.value = content;
  listQuestionBank(1);
}

function deleteBatchQuestionBank() {
  confirmVisible.value = true;
}

async function editQuestionBank(bankId) {
  const result = await getQuestionBankVOByIdUsingGet(bankId);
  editBankInfo.value = result.data.data;
  editVisible.value = true;
  curOperate = "update";
}

function deleteQuestionBank(id) {
  delBankId.value = id;
  confirmVisible.value = true;
}

// 进行删除操作
async function doDeleteBank() {
  if (delBankId.value !== 0) {
    await deleteQuestionBankUsingPost({
      id: delBankId.value
    });
    delBankId.value = 0;
  } else if (selectedKeys.value.length > 0) {
    await deleteBatchQuestionBankUsingPost({
      ids: selectedKeys.value
    });
    selectedKeys.value = [];
  }
  await listQuestionBank(pageInfo.value.current);
}

// 进行更新操作
async function doEditBank() {
  if(curOperate === 'update') {
    if(file.value){
      const result = await uploadFileUsingPost(file.value , "bank_icon");
      editBankInfo.value.bankIcon = result.data.data;
    }
    await updateQuestionBankUsingPost(editBankInfo.value);
  }else if(curOperate === 'add') {
    if(file.value){
      const result = await uploadFileUsingPost(file.value , "bank_icon");
      editBankInfo.value.bankIcon = result.data.data;
    }
    await addQuestionBankUsingPost(editBankInfo.value);
  }
  await clearContent();
  await listQuestionBank(pageInfo.value.current);
  file.value = null;
}

// 清空弹窗中输入的内容
async function clearContent() {
  editVisible.value = false;
  editBankInfo.value = {
    title: '',
    tags: []
  };
}

// 移除标签
const handleRemove = (key) => {
  editBankInfo.value.tags = editBankInfo.value.tags.filter((tag) => tag !== key);
};

// 添加标签
const handleAdd = () => {
  if (inputVal.value) {
    editBankInfo.value.tags.push(inputVal.value);
    inputVal.value = '';
  }
  showInput.value = false;
};

const handleEdit = () => {
  showInput.value = true;

  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus();
    }
  });
};

function addQuestionBank(){
  editVisible.value = true;
  curOperate = "add";
}

function onProgress(currentFile){
  file.value = currentFile.file;
  console.log(currentFile.file);
}
</script>

<style scoped>
/* 搜索框样式 */
.search {
  width: 360px;
}

/* 搜索框容器样式 */
.search-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
</style>